package com.living.filedownloader;

import android.app.Application;
import android.content.Context;
import android.text.TextUtils;

import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadMonitor;
import com.liulishuo.filedownloader.FileDownloader;
import com.liulishuo.filedownloader.connection.FileDownloadUrlConnection;
import com.liulishuo.filedownloader.util.FileDownloadLog;
import com.liulishuo.filedownloader.util.FileDownloadUtils;
import com.living.BuildConfig;
import com.living.filedownloader.bean.TasksManagerModel;
import com.living.filedownloader.db.AlbumDB;
import com.living.filedownloader.db.AudioDB;
import com.living.filedownloader.db.DownLoadDBManger;
import com.living.filedownloader.ui.adapter.TaskItemViewHolder;
import com.living.player.services.MediaPlayerServiceImp;
import com.md.network.api.Album;
import com.md.network.api.Audio;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 提供对外接入的能力
 * 下载管理 入口
 */
public class DownLoadManger {

    public static DownLoadManger instance = null;
    public static Application application;
//    private List<TasksManagerModel> modelList = new ArrayList<>();

    public static DownLoadManger getInstance() {
        if (instance == null) {
            instance = new DownLoadManger();
        }
        return instance;
    }

    /***
     * 初始化 原生下载组件
     **/
    public static void init(Application application) {
        FileDownloadLog.NEED_LOG = BuildConfig.DEBUG;
        /**
         * 下载队列的配置
         */
        FileDownloader.setupOnApplicationOnCreate(application)
                .maxNetworkThreadCount(1)      // 下载队列 -- 同时下载的个数
                .connectionCreator(new FileDownloadUrlConnection
                        .Creator(new FileDownloadUrlConnection.Configuration()
                        .connectTimeout(15000) // 设置连接超时时间
                        .readTimeout(15000)    // 读取超时时间
                ))
                .commit();
        // 这是只是为了全局监控。如果你有需求需要全局监控（比如用于打点/统计）可以使用这个方式，如果没有类似需求就不需要  如果你有这个需求，实现FileDownloadMonitor.IMonitor接口，也使用FileDownloadMonitor.setGlobalMonitor注册进去即可
        FileDownloadMonitor.setGlobalMonitor(GlobalTaskMonitor.getImpl());
        DownLoadManger.getInstance().initData();
        // 播放初始化
        MediaPlayerServiceImp.intentToStart(application);
    }


    private void initData() {
        // modelList = DownLoadDBManger.getInstance().getAllTasks();
    }

    /***
     * 批量加入
     * @param album
     * @param audioList
     */
    public void downloadAudioList(Album album, ArrayList<Audio> audioList) {
        AlbumDB albumDB = new AlbumDB();
        albumDB.setId(album.getId());
        albumDB.setName(album.getName());
        albumDB.setDesc(album.getDesc());
        albumDB.setAuthor(album.getAuthor());
        albumDB.setCover(album.getCoverUrl());
        albumDB.setCreate_time(System.currentTimeMillis());
        albumDB.setUpdatete_time(System.currentTimeMillis());
        List<AudioDB> audioDBS = new ArrayList<>();
        for (Audio audio : audioList) {
            AudioDB audioDB = new AudioDB();
            audioDB.setAlbum_id(album.getId());
            audioDB.setAlbum_name(album.getName());
            audioDB.setId(audio.getId());
            String path = createPath(audio.getAudioUrl());
            // 保证生成的ID一支和唯一性
            BaseDownloadTask task = FileDownloader.getImpl()
                    .create(audio.getAudioUrl())
                    .setPath(DownLoadManger.createPath(audio.getAudioUrl()))
                    .setCallbackProgressTimes(TaskItemViewHolder.callbackProgressTimes);
            audioDB.setPath(task.getPath());
            audioDB.setTaskId(task.getId());
            audioDB.setUrl(audio.getAudioUrl());
            audioDB.setName(audio.getName());
            audioDB.setAuthor(audio.getAuthor());
            audioDB.setCover(audio.getCoverUrl());
            audioDB.setDesc(audio.getDesc());

            audioDB.setCreate_time(System.currentTimeMillis());
            audioDB.setUpdatete_time(System.currentTimeMillis());
            audioDBS.add(audioDB);

            // 启动下载任务
            task.start();
            GlobalTasksManager.getInstance().addTaskForViewHolder(task);
        }
        DownLoadDBManger.getInstance().saveAudioList(albumDB, audioDBS);
        DownLoadManger.getInstance().initData();
    }

    /***
     * 批量加入
     * @param audioList
     */
    public void downloadAudioList(ArrayList<Audio> audioList) {
//        List<AudioDB> audioDBS = new ArrayList<>();
        for (Audio audio : audioList) {
            AlbumDB albumDB = new AlbumDB();
            albumDB.setId(audio.getAlbumId());
            albumDB.setName(audio.getAlbumName());
            albumDB.setDesc(audio.getAlbumDes());
            albumDB.setAuthor(audio.getAlbumAuthor());
            albumDB.setCover(audio.getAlbumDes());
            albumDB.setCreate_time(System.currentTimeMillis());
            albumDB.setUpdatete_time(System.currentTimeMillis());

            AudioDB audioDB = new AudioDB();
            audioDB.setAlbum_id(audio.getAlbumId());
            audioDB.setAlbum_name(audio.getAlbumName());
            audioDB.setId(audio.getId());
            String path = createPath(audio.getAudioUrl());
            // 保证生成的ID一支和唯一性
            BaseDownloadTask task = FileDownloader.getImpl()
                    .create(audio.getAudioUrl())
                    .setPath(DownLoadManger.createPath(audio.getAudioUrl()))
                    .setCallbackProgressTimes(TaskItemViewHolder.callbackProgressTimes);
            audioDB.setPath(task.getPath());
            audioDB.setTaskId(task.getId());
            audioDB.setUrl(audio.getAudioUrl());
            audioDB.setName(audio.getName());
            audioDB.setAuthor(audio.getAuthor());
            audioDB.setCover(audio.getCoverUrl());
            audioDB.setDesc(audio.getDesc());

            audioDB.setCreate_time(System.currentTimeMillis());
            audioDB.setUpdatete_time(System.currentTimeMillis());
//            audioDBS.add(audioDB);

            // 启动下载任务
            task.start();
            GlobalTasksManager.getInstance().addTaskForViewHolder(task);

//            DownLoadDBManger.getInstance().saveAudioList(albumDB, audioDBS);

            DownLoadDBManger.getInstance().saveAudioAblum(albumDB, audioDB);
        }

        DownLoadManger.getInstance().initData();
    }


    /**
     * 开启下载任务
     *
     * @param url
     */
    public void startDownload(String url) {
        // 保证生成的ID一支和唯一性
        BaseDownloadTask task = FileDownloader.getImpl()
                .create(url)
                .setPath(DownLoadManger.createPath(url))
                .setCallbackProgressTimes(TaskItemViewHolder.callbackProgressTimes);
        // 启动下载任务
        task.start();
        GlobalTasksManager.getInstance().addTaskForViewHolder(task);
    }

    public List<TasksManagerModel> getDownloadedList() {
        return DownLoadDBManger.getInstance().getDownloadedTasks();
    }

    public List<TasksManagerModel> getDownloadingList() {
        return DownLoadDBManger.getInstance().getDownloadingTasks();
    }

    public void deleteAudio(String albumId, String audio_id, String url) {
        String path = createPath(url);
        // 保证生成的ID一支和唯一性
        BaseDownloadTask task = FileDownloader.getImpl().create(url).setPath(path);
        DownLoadDBManger.getInstance().deleteAudio(albumId, audio_id);
        // 校验是否可以删除文件
        if (DownLoadDBManger.getInstance().checkDeleteAudioId(audio_id)) {
            File file = new File(task.getPath());
            if (file.exists()) {
                file.delete();
            }
        }
    }

    /**
     * 判断 是否下载
     *
     * @return
     */
    public boolean isAudioExite(String albumId, String audioId) {
        return DownLoadDBManger.getInstance().isAudioExite(albumId, audioId);
    }

    /**
     * 应用程序销毁调用
     */
    protected void onDestroy() {
        TasksManager.getImpl().onDestroy();
        FileDownloader.getImpl().pauseAll();
        FileDownloader.getImpl().unBindServiceIfIdle();
        FileDownloadMonitor.releaseGlobalMonitor();
    }

    public static String createPath(final String url) {
        if (TextUtils.isEmpty(url)) {
            return null;
        }
        return FileDownloadUtils.getDefaultSaveFilePath(url);
    }


}
